package com.huel.fragment;

import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.huel.bean.Goods;
import com.huel.bean.Item;
import com.huel.components.ItemRecycleViewAdapter;
import com.huel.components.MyRecyclerViewAdapter;
import com.huel.components.RecyclerItemClickListener;
import com.huel.dao.ItemsDao;
import com.huel.taobaostore.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Cart_Fragment extends Fragment {
    private RecyclerView recyclerView;
    private ItemRecycleViewAdapter cartRecycleViewAdapet;
    private  View contextView;
    private TextView count ;
    private Button goBtn;
    private List<Goods> mList = new ArrayList<>();
    private List<String>tempList =new ArrayList<>();
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    // 创建view   也可以直接在这里面获取view中的控件。
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        contextView = inflater.inflate(R.layout.fragment_cart, container, false);
        //获取控件
        recyclerView = contextView.findViewById(R.id.cart);
        count =contextView.findViewById(R.id.goodsCnt);

        goBtn=contextView.findViewById(R.id.goBtn);
        cartRecycleViewAdapet = new ItemRecycleViewAdapter(mList);
        recyclerView.setAdapter(cartRecycleViewAdapet);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false);
        recyclerView.setLayoutManager(linearLayoutManager);
        initData();

        goBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                View view01 = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_show_pic, null);
                final Dialog dialog = builder.create();
                dialog.show();
                dialog.getWindow().setContentView(view01);
            }
        });


        recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, final int position) {
                ImageView delete = view.findViewById(R.id.delete);
                ImageView up = view.findViewById(R.id.updateCnt);
                delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //在这点击删除
                       //请求服务器
                    }
                });
                up.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                        View view01 = LayoutInflater.from(getActivity()).inflate(R.layout.update_dialog, null);
                        TextView cancel = view01.findViewById(R.id.choosepage_cancel);
                        TextView sure = view01.findViewById(R.id.choosepage_sure);
                        final EditText edittext = view01.findViewById(R.id.input_cnt);
                        final Dialog dialog = builder.create();
                        dialog.show();
                        dialog.getWindow().setContentView(view01);
                        //使editext可以唤起软键盘
                        dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
                        cancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                            }
                        });
                        sure.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Toast.makeText(getActivity(), "修改成功", Toast.LENGTH_SHORT).show();
                                //请求服务器
                                dialog.dismiss();
                            }
                        });
                    }

                });
                cartRecycleViewAdapet.notifyDataSetChanged();
            }
        }));
        return contextView;
    }

    public void   initData(){

        //请求 所有 购物车的信息
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://192.168.199.229:8080/Android_war_exploded/cart?action=showItems&username=2580" )
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //失败回调
                System.out.println("请检查网络");
            }
            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                //响应成功,这个回调在子线程中,所以不需要创建线程
                String json =response.body().string();//注意response.body().string() 只能调用一次！
                if (response.isSuccessful()) {
                    //isSuccessful方法：如果代码位于（200…300）中，则返回true，这意味着请求已成功接收
                    //在这写  更新UI操作
                    try{
                        String goods_count;
                        mList.clear();
                        JSONArray jsonArray = null;
                        jsonArray = new JSONArray(json);
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject = null;
                            jsonObject = jsonArray.getJSONObject(i);
                            if (jsonObject != null) {
                                System.out.println(jsonObject);
                                int id = jsonObject.optInt("c_id");
                                String name = jsonObject.optString("c_name");
                                double price = jsonObject.optDouble("c_price");
                                String details = jsonObject.optString("details");
                                String imagePath = jsonObject.optString("c_img");
                                // 封装Java对象
                                Goods good = new Goods(id, name, price, imagePath, details);
                                goods_count=jsonObject.optString("total_count");
                                tempList.add(goods_count);
                                System.out.println("网络地址：" + good.getPic());
                                mList.add(good);
                                //添加到类中
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            cartRecycleViewAdapet.notifyDataSetChanged();
                            count.setText("共"+tempList.get(0)+"件商品");
                        }
                    });
                }

            }


        });

    }


}
